package com.mornd.controller;

import com.mornd.annotation.LogStar;
import com.mornd.entity.LoginUser;
import com.mornd.service.UserService;
import com.mornd.utils.IdUtil;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mornd
 * @date 2021/1/14 - 23:57
 * 文件上传控制层
 */
@Controller
@RequestMapping("file")
public class FileController {
    //如果该注解为null，则用默认路径
    @Value("${file.upload.avatarPath}")
    private String avatarPath = "E:/upload/boot_summer/avatar/";

    //默认图片路径
    private final String DEFAULT_IMAGE = "default.jpg";

    @Lazy
    @Resource
    private UserService userService;

    /**
     * 文件上传
     * @param file 文件对象
     * @return
     */
    @LogStar("上传文件")
    @ResponseBody
    @PostMapping("/upload")
    public Map upload(MultipartFile file){
        Map<String,Object> map = new HashMap<>();
        if(file.isEmpty()){
            map.put("isEmpty",true);
            map.put("message","文件不能为空！");
            return map;
        }
        //1、获取文件名称
        String fileName = file.getOriginalFilename();
        //2、获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //3、使用UUID重命名文件名称
        String newFileName = IdUtil.getUUID() + suffix;
        //4、使用日期解决同一文件夹中文件过多问题（以当前日期命名文件夹）
        String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //5、组装最终文件名
        String finalName = datePath +"/" + newFileName;
        //6、构建文件对象
        File dirFile = new File(avatarPath,finalName);
        //7、判断该文件夹是否存在，不存在则创建
        if (!dirFile.getParentFile().exists()) {
            dirFile.getParentFile().mkdirs();
        }
        try {
            //8、存放图片
            file.transferTo(dirFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //回显路径
        map.put("path",finalName);
        map.put("message","文件上传成功！");

        //修改数据库信息
        LoginUser user = new LoginUser();
        user.setAvatar(finalName);
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        user.setId(loginUser.getId());
        userService.updateById(user);

        return map;
    }

    /**
     * 文件下载
     * @param path 文件路径
     * @return
     */
    @LogStar("下载图片")
    @ResponseBody
    @RequestMapping("/downLoad")
    public ResponseEntity<Object> downLoad(String path){
        //构建文件对象
        File file = new File(avatarPath,path);
        if(!file.exists()){
            //读取默认图片
            file = new File(avatarPath,DEFAULT_IMAGE);
        }
        //将下载的文件封装成byte数组
        byte[] bytes = null;
        try {
            bytes = FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建封装响应头信息
        HttpHeaders header = new HttpHeaders();
        //封装响应内容类型
        header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //设置下载文件的名称(可选)
        //header.setContentDispositionFormData("","");;
        //创建ResponseEntity对象
        ResponseEntity responseEntity = new ResponseEntity(bytes, HttpStatus.CREATED);
        return responseEntity;
    }
}
